package com.csxy.six.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csxy.six.dto.FoundItemDTO;
import com.csxy.six.entity.FoundItem;
import com.csxy.six.mapper.FoundItemMapper;
import com.csxy.six.service.FoundItemService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class FoundItemServiceImpl extends ServiceImpl<FoundItemMapper, FoundItem> implements FoundItemService {

    @Override
    @Transactional
    public FoundItem addFoundItem(FoundItemDTO foundItemDTO) {
        FoundItem foundItem = new FoundItem();
        BeanUtils.copyProperties(foundItemDTO, foundItem);
        foundItem.setIsClaimed(false);
        this.save(foundItem);
        return foundItem;
    }

    @Override
    public List<FoundItem> getAllFoundItems() {
        return this.list(new QueryWrapper<FoundItem>().orderByDesc("created_at"));
    }

    @Override
    public FoundItem getFoundItemById(Integer foundId) {
        return this.getById(foundId);
    }

    @Override
    @Transactional
    public FoundItem updateFoundItem(Integer foundId, FoundItemDTO foundItemDTO) {
        FoundItem existingItem = this.getById(foundId);
        if (existingItem == null) {
            throw new RuntimeException("未找到ID为" + foundId + "的拾物记录");
        }
        BeanUtils.copyProperties(foundItemDTO, existingItem, "foundId", "isClaimed", "createdAt");
        this.updateById(existingItem);
        return existingItem;
    }

    @Override
    @Transactional
    public void deleteFoundItem(Integer foundId) {
        this.removeById(foundId);
    }

    @Override
    public List<FoundItem> getFoundItemsByPublisher(Long publisherId) {
        return this.list(new QueryWrapper<FoundItem>()
                .eq("publisher_id", publisherId)
                .orderByDesc("created_at"));
    }

    @Override
    @Transactional
    public FoundItem markAsClaimed(Integer foundId) {
        FoundItem foundItem = this.getById(foundId);
        if (foundItem == null) {
            throw new RuntimeException("未找到ID为" + foundId + "的拾物记录");
        }
        foundItem.setIsClaimed(true);
        this.updateById(foundItem);
        return foundItem;
    }
}